package com.mall.book.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.book.entity.po.*;
import com.mall.book.service.*;
import com.mall.book.service.impl.AuthorInfoService;
import com.mall.book.wrapper.ResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Dizziness on 2022/4/15 10:21
 */
@Controller
public class ManagementCenter {
    @Autowired
    BookInfoService bookInfoService;

    @Autowired
    SaleStockService saleStockService;

    @Autowired
    CategoryInfoService categoryInfoService;

    @Autowired
    CategoryGroupInfoService categoryGroupInfoService;

    @Autowired
    BookCategoryRelationshipService bookCategoryRelationshipService;

    @Autowired
    AuthorInfoService authorInfoService;

    @Autowired
    BookAuthorRelationshipService bookAuthorRelationshipService;

    /**
     * 添加商品
     * 功能：
     */
    @PostMapping("/manage/addItem")
    @Transactional
    @ResponseBody
    public ResultWrapper addItem(HttpServletRequest request){
        String data = request.getParameter("data");
        //组装sku信息
        Map<String, Object> params = (Map)JSON.parse(data);
        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookTitle((String) params.get("title"));
        bookInfo.setBookPrice(Float.valueOf((BigDecimal) params.get("price") + ""));
        bookInfo.setBookPublisher((String) params.get("publisher"));
        bookInfo.setBookPublicationTime((Date) params.get("publiction_time"));
        bookInfo.setBookVersion((int) params.get("version"));
        bookInfo.setBookTotalPage((int) params.get("total_page"));
        bookInfo.setBookLanguage((String) params.get("language"));
        bookInfo.setBookIsbn((String) params.get("isbn"));
        bookInfo.setBookCover((String) params.get("cover"));
        bookInfo.setBookProfile((String) params.get("profile"));

        boolean save = bookInfoService.save(bookInfo);
        if(!save) {
            throw new RuntimeException("sku存储失败");
        }
        //存储与类目之间的关系
        BookCategoryRelationship relationship = new BookCategoryRelationship();
        relationship.setBookId(bookInfo.getBookId());
        relationship.setCategoryId((String) params.get("category"));
        save = bookCategoryRelationshipService.save(relationship);
        if(!save) {
            throw new RuntimeException("存储书籍与类目关系失败");
        }
        //存作者列表
        List<Map<String, Object>> authors = (List)params.get("authors");
        for (Map<String, Object> map : authors) {
            AuthorInfo authorInfo = new AuthorInfo();
            authorInfo.setAuthorName((String) map.get("name"));
            authorInfo.setAuthorNationality((String) map.get("nationality"));

            save = authorInfoService.save(authorInfo);
            if (!save) {
                throw new RuntimeException("存储作者信息失败");
            }
            BookAuthorRelationship baship = new BookAuthorRelationship();
            baship.setBookId(bookInfo.getBookId());
            baship.setAuthorId(authorInfo.getAuthorId());
            save = bookAuthorRelationshipService.save(baship);
            if (!save) {
                throw new RuntimeException("存储书籍与作者关系失败");
            }
        }

        //存在售库存
        SaleStock saleStock = new SaleStock();
        saleStock.setBookId(bookInfo.getBookId());
        saleStock.setOnSale((int)params.get("stock"));
        save = saleStockService.save(saleStock);
        if(!save) {
            throw new RuntimeException("更新库存信息失败");
        }

        return ResultWrapper.builder().code(200).msg("添加商品成功").build();
    }

    /**
     * 添加类目分组
     */
    @PostMapping("/manage/addGroup")
    @ResponseBody
    public ResultWrapper addGroup(HttpServletRequest request) {
        String name = request.getParameter("name");
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("group_name", name);
        Collection<CategoryGroupInfo> groupInfos = categoryGroupInfoService.getByMap(queryMap);
        if (groupInfos.size() > 0) {
            return ResultWrapper.builder().code(201).msg("已有同名分组").build();
        }

        CategoryGroupInfo group = new CategoryGroupInfo();
        group.setGroupName(name);
        group.setGroupProfile(request.getParameter("profile"));
        boolean save = categoryGroupInfoService.save(group);

        if (!save) {
            return ResultWrapper.builder().code(202).msg("新增分组失败").build();
        }
        queryMap.remove("group_name");
        queryMap.put("id", group.getGroupId());
        queryMap.put("name", group.getGroupName());
        queryMap.put("profile", group.getGroupProfile());
        return ResultWrapper.builder().code(200).msg("新增分组成功").data(queryMap).build();
    }

    /**
     * 添加类目
     */
    @PostMapping("/manage/addCategory")
    @ResponseBody
    public ResultWrapper addCategory(HttpServletRequest request) {
        String name = request.getParameter("name");
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("category_name", name);

        Collection<CategoryInfo> categoryInfos = categoryInfoService.getByMap(queryMap);
        if (categoryInfos.size() > 0) {
            return ResultWrapper.builder().code(201).msg("已有同名类目").build();
        }

        String group = request.getParameter("group");
        String profile = request.getParameter("profile");

        CategoryInfo categoryInfo = new CategoryInfo();
        categoryInfo.setCategoryName(name);
        categoryInfo.setGroupId(group);
        categoryInfo.setCategoryProfile(profile);

        boolean save = categoryInfoService.save(categoryInfo);
        if (!save) {
            return ResultWrapper.builder().code(202).msg("存储失败").build();
        }

        queryMap.remove("category_name");
        queryMap.put("id", categoryInfo.getCategoryId());
        queryMap.put("name", categoryInfo.getCategoryName());
        queryMap.put("profile", categoryInfo.getCategoryProfile());

        return ResultWrapper.builder().code(200).msg("添加成功").data(queryMap).build();
    }

    /**
     * 获取类目
     */
    @PostMapping("/manage/getCategories")
    @ResponseBody
    public ResultWrapper getCategories(HttpServletRequest request) {
        String id = request.getParameter("id");
        HashMap<String, Object> queryMap = new HashMap<>();
        queryMap.put("group_id", id);

        Collection<CategoryInfo> categoryInfos = categoryInfoService.getByMap(queryMap);

        ArrayList<Map> result = new ArrayList<>();
        for (CategoryInfo categoryInfo : categoryInfos) {
            HashMap<String, Object> wrapper = new HashMap<>();
            wrapper.put("id", categoryInfo.getCategoryId());
            wrapper.put("name", categoryInfo.getCategoryName());
            wrapper.put("profile", categoryInfo.getCategoryProfile());

            result.add(wrapper);
        }

        return ResultWrapper.builder().code(200).msg("获取类目成功").data(result).build();
    }

    /**
     * 获取分组
     */
    @PostMapping("/manage/getGroups")
    @ResponseBody
    public ResultWrapper getGroups(HttpServletRequest request) {
        List<CategoryGroupInfo> groupInfos = categoryGroupInfoService.getAll();

        ArrayList<Map> result = new ArrayList<>();
        for (CategoryGroupInfo groupInfo : groupInfos) {
            HashMap<String, Object> wrapper = new HashMap<>();
            wrapper.put("id", groupInfo.getGroupId());
            wrapper.put("name", groupInfo.getGroupName());
            wrapper.put("profile", groupInfo.getGroupProfile());

            result.add(wrapper);
        }
        return ResultWrapper.builder().code(200).msg("获取成功").data(result).build();
    }


    /**
     * 商品上下架
     */
    @PostMapping("/manage/statusChange")
    @ResponseBody
    public ResultWrapper statusChange(HttpServletRequest request) {
        String id = request.getParameter("id");
        int status = Integer.valueOf(request.getParameter("status"));

        boolean update = saleStockService.changeDeletedStatus(id, status);

        if (!update) {
            return ResultWrapper.builder().code(201).msg("操作失败").build();
        }

        return ResultWrapper.builder().code(200).msg("操作成功").build();
    }

    /**
     * 补货
     */
    @PostMapping("/manage/replenishment")
    @ResponseBody
    public ResultWrapper replenishment(HttpServletRequest request) {
        String book_id = request.getParameter("book_id");
        int quantity = Integer.valueOf(request.getParameter("quantity"));

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("book_id", book_id);

        SaleStock saleStock = saleStockService.getOne(queryWrapper);

        UpdateWrapper updateWrapper = new UpdateWrapper();
        int new_stock = saleStock.getOnSale() + quantity;
        updateWrapper.set("on_sale", new_stock);
        updateWrapper.eq("book_id", book_id);
        boolean update = saleStockService.update(updateWrapper);
        if (!update) {
            return ResultWrapper.builder().code(201).msg("补货失败").build();
        }
        return ResultWrapper.builder().code(200).msg("商品" + book_id + "补货" + quantity + "本成功").data(new_stock).build();
    }

    /**
     * 获取商品信息(带搜索)
     * sku + sale_stock
     */
    @PostMapping("/manage/getGoods")
    @ResponseBody
    public ResultWrapper getGoods(HttpServletRequest request) {
        ArrayList<Map> goods = new ArrayList<>();

        //查出所有的商品包括已删除的
        Long current = Long.valueOf(request.getParameter("current"));
        Long size = Long.valueOf(request.getParameter("size"));
        Page<BookInfo> page = new Page<>(current, size);

        QueryWrapper queryWrapper = new QueryWrapper();
        String keyword = request.getParameter("keyword");
        if(keyword != null && keyword.length() != 0) {
            StringBuilder sb = new StringBuilder("%");
            for (char c : keyword.toCharArray()) {
                sb.append(c + "%");
            }
            queryWrapper.like("book_title", sb.toString());
        }

        page = bookInfoService.page(page, queryWrapper);
        List<BookInfo> bookInfos = page.getRecords();

        for (BookInfo bookInfo : bookInfos) {
            String book_id = bookInfo.getBookId();
            //查找到每一本书的销售库存信息
            HashMap<String, Object> wrapper = new HashMap<>();
            wrapper.put("id", book_id);
            wrapper.put("title", bookInfo.getBookTitle());
            wrapper.put("price", bookInfo.getBookPrice());
            wrapper.put("cover", bookInfo.getBookCover());
            wrapper.put("isbn", bookInfo.getBookIsbn());
            wrapper.put("updating", false);
            wrapper.put("quantity", 0);

            SaleStock saleStock = saleStockService.getStock(book_id);
            if (saleStock == null) {
                wrapper.put("un_sale", "1");//商品未上架过,前端就需要先补货，再上架
            } else {
                wrapper.put("on_sale", (int) saleStock.getOnSale());
                wrapper.put("locking", (int) saleStock.getLocking());
                wrapper.put("sold", (int) saleStock.getSold());
                wrapper.put("deleted", saleStock.getDeleted() + "");
            }

            goods.add(wrapper);
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("goods", goods);
        result.put("total", page.getTotal());

        return ResultWrapper.builder().code(200).msg("获取库存成功").data(result).build();
    }
}
